package com.qj.yantaishan.common.utils;

import lombok.SneakyThrows;
import org.apache.poi.ss.formula.functions.T;
import org.phprpc.util.PHPSerializer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * php序列化工具
 */
public class PhpSerializerUtils {


    @SneakyThrows
    public static Object unSerializer(String obj, Class cls) {
        if (StringUtils.isEmpty(obj)) throw new NullPointerException("传入要反序列化的值不能为空");
        org.phprpc.util.PHPSerializer ps = new PHPSerializer();
        Object result = ps.unserialize(obj.getBytes(), cls);

        return result;
    }

    @SneakyThrows
    public static String serializer(Object t) {
        if (t == null) throw new NullPointerException("传入要序列化的值不能为空");
        String objArray = objectToPhpSerializer(t);

        return objArray;
    }


    @SneakyThrows
    static String objectToPhpSerializer(Object obj) {
        PHPSerializer phpSerializer = new PHPSerializer();
        Map<String, String> map = new HashMap<>();
        if (obj == null) throw new NullPointerException("你传个屁，空的？");
        //获取到每个字段 和对应的值
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取字段的值
            String value = field.get(obj).toString();
            //获取字段属性名称
            String name = field.getName();
            map.put(name, value);
        }
        byte[] serialize = phpSerializer.serialize(map);
        return new String(serialize);
    }
}